//引入pinia
import { defineStore } from 'pinia'
import { login } from '@/api/login'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

//创建store
export const userStore = defineStore('localUser', () => {
  // 定义管理用户数据的state
  const id = ref(0)
  const username = ref('')
  const name = ref('')
  const token = ref('')
  const isLogin = ref(false)

  // 定义获取接口数据的action函数
  const userLogin = async (data: any) => {
    //执行登录
    const result = await login(data) as any
    //登录成功
    if (result.code === 1) {
      id.value = result.data.id
      username.value = result.data.username
      name.value = result.data.name
      isLogin.value = true as boolean;
      token.value = result.data.token

      //信息提示
      ElMessage({
        showClose: true,
        message: result.msg,
        type: 'success',
      })
    } else {
      //登录失败，提示错误信息
      ElMessage({
        showClose: true,
        message: result.msg,
        type: 'error',
      })
    }
  }

  //登出方法
  const userLoginOut = () => {
    id.value = 0
    name.value = ''
    username.value = ''
    isLogin.value = false as boolean;
    token.value = null as any;
  }

  // 以对象形式把state和action return
  return { id, username, name, userLogin, userLoginOut, token, isLogin }
},
  //持久化配置
  {
    persist: true,
  }
)